<template>
  <div>
    <a-modal
      title="地图"
      v-model:open="dialogShow"
      width="50.5%"
      @cancel="closeMap"
      @ok="onSubmit"
      :maskClosable="false"
      :destroyOnClose="true"
      style="height: 600px"
      :footer="null"
    >
      <div class="map">
        <a-row class="map-search margin-left2">
          <a-col :span="9">
            <span>公司地址</span>
            <a-input
              v-model="searchQuery"
              id="tipinput"
              class="margin-left2"
              style="width: 72%"
              placeholder="当前地图选中地址/手动输入的地址"
            ></a-input>
            <div id="tip"></div>
          </a-col>
          <a-col :span="9">
            <div class="location">
              <span>经纬度</span>
              <a-input
                disabled
                class="margin-left2"
                style="width: 72%"
                id="lnglats"
                ref="myElement"
              ></a-input>
            </div>
          </a-col>
        </a-row>
      </div>
      <div id="container" style="width: 100%; height: 418px; margin-bottom: 20px"></div>

      <div class="btn">
        <a-space :size="12">
          <a-button @click="closeMap">取 消</a-button>
          <a-button type="primary" @click="onSubmit" v-if="props?.mapUpdFlag == 1">确定</a-button>
        </a-space>
      </div>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, watch, computed, type Ref } from 'vue';
  import { shallowRef } from '@vue/reactivity';
  import AMapLoader from '@amap/amap-jsapi-loader';
  import Geocoder from '@amap/amap-jsapi-loader';
  const props = defineProps(['dialogMap', 'valueMap', 'longiTudeMap', 'latiTudeMap', 'mapUpdFlag']);
  const emit = defineEmits(['closeMap', 'submitMap', 'update:dialogVisible']);
  // eslint 不允许在子级修改父级的数据，限制修改 dialogVisible
  const dialogShow = computed({
    get: () => props.dialogMap,
    set: (val) => emit('update:dialogVisible', val),
  });
  const map = shallowRef(null) as any;
  const path = ref<any>([]);
  const POIList = ref<any>([]);
  const searchQuery = ref('');
  const geocoder = ref<any>(null);
  const marker = ref<any>(null);
  const POISearch = ref<any>(null);
  const current_position = ref<any>([]);
  const POIMarkers = ref<any>([]);
  const hotspot = ref<any>([]);
  const hotspotName = ref<any>([]);
  const clickValue = ref<any>([]);
  const clickArray = ref<any>([]);
  let positions = {
    lng: '',
    lat: '',
  };
  const myElement: Ref<any> = ref();

  //  搜索提示
  let autoOptions = {
    city: '全国',
    input: 'searchQuery', // 绑定输入提示功能的input的DOM ID
    // output: 'tip',
  };

  const initMap = () => {
    AMapLoader.load({
      key: '1014378f1b2152e79709b92d9b7dfa71', // 申请好的Web端开发者Key，首次调用 load 时必填
      version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        'AMap.Geocoder',
        'AMap.AutoComplete',
        'AMap.ToolBar',
        'AMap.PlaceSearch',
        'AMap.Geolocation',
        'AMap.CitySearch',
      ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
      .then((AMap) => {
        map.value = new AMap.Map('container', {
          //设置地图容器id
          pitch: 25, // 地图俯仰角度，有效范围 0 度- 83 度
          viewMode: '3D', //是否为3D地图模式
          zoom: 14, //初始化地图级别
          // center: [112.93, 28.23], //初始化地图中心点位置
          resizeEnable: true,
          keyboardEnable: false,
        });
        // map.setZoomAndCenter(14, [116.205467, 39.907761]);

        function initialAddress() {
          if (props.valueMap != '') {
            const mapValue = [parseFloat(props.longiTudeMap), parseFloat(props.latiTudeMap)];

            if (myElement.value) {
              positions.lng = props.longiTudeMap;
              positions.lat = props.latiTudeMap;

              // 使用 getElementById 获取元素
              let element = document.getElementById('lnglats') as any;
              if (element) {
                // 在这里对元素进行操作
                setTimeout(() => {
                  element.value = positions.lng + ',' + positions.lat;
                }, 200);
              }
            }

            var m1 = new AMap.Marker({
              position: mapValue,
              center: mapValue,
              icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
              anchor: 'bottom-center',
            });
            map.value.add(m1);
            m1.setLabel({
              content: '编辑前的位置',
            });
            map.value.setCenter(new AMap.LngLat(mapValue[0], mapValue[1]));
          } else {
            // 获取当前位置
            // var geolocation = new AMap.Geolocation({
            //   zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            // });
            // map.addControl(geolocation);
            // geolocation.getCurrentPosition();
            // //返回定位信息
            // AMap.event.addListener(geolocation, 'complete'); // onComplete

            AMap.plugin('AMap.CitySearch', function () {
              var citySearch = new AMap.CitySearch();
              citySearch.getLocalCity(function (status, result) {
                if (status === 'complete' && result.info === 'OK') {
                  // 查询成功，result即为当前所在城市信息
                }
              });
            });
          }
        }
        initialAddress();
        AMap.plugin('AMap.Geocoder', () => {
          geocoder.value = new AMap.Geocoder();
        });

        AMap.plugin('AMap.ToolBar', () => {
          var toolBar = new AMap.ToolBar({
            autoPosition: true, //自定位
            locate: false,
            // locationMarker:this.marker,//自定义定位图标，值为Marker对象
          }); //工具条，控制地图的缩放、平移等
          map.value.addControl(toolBar);
          toolBar.show();
        });
        // map.on('hotspotover', (e) => {
        //   hotspot.value = e.lnglat;
        // });

        map.value.on('hotspotclick', (e) => {
          if (!e && !e.lnglat) {
            return;
          }
          hotspot.value = [e.lnglat.lng, e.lnglat.lat];
          addMarker('hotspotclick');
        });

        map.value.on('click', (e) => {
          if (!e && !e.lnglat) {
            return;
          }
          clickValue.value = [e.lnglat.lng, e.lnglat.lat];
          addMarker('click');
        });

        function addMarker(e) {
          clearMarker();
          map.value.remove(POIMarkers.value);

          clickArray.value.push(e);

          if (clickArray.value[0] == 'hotspotclick') {
            marker.value = new AMap.Marker({
              position: hotspot.value, // 这里我们通过上面的点击获取经纬度坐标,实时添加标记
              anchor: 'bottom-center',
            });
            map.value.setZoomAndCenter(18, hotspot.value);
            map.value.add(marker.value);
            current_position.value = hotspot.value;
            path.value = hotspot.value;

            if (myElement.value) {
              positions.lng = hotspot.value[0];
              positions.lat = hotspot.value[1];

              // 使用 getElementById 获取元素
              let element = document.getElementById('lnglats') as any;
              if (element) {
                // 在这里对元素进行操作
                element.value = positions.lng + ',' + positions.lat;
              }
            }
          } else if (clickArray.value[0] == 'click') {
            marker.value = new AMap.Marker({
              // icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
              position: clickValue.value, // 这里我们通过上面的点击获取经纬度坐标,实时添加标记
              // 通过设置 offset 来添加偏移量
              // offset: new AMap.Pixel(-19, -63),
              // imageSize: new AMap.Size(38, 63),
              anchor: 'bottom-center',
            });
            map.value.setZoomAndCenter(18, clickValue.value);
            map.value.add(marker.value);
            current_position.value = clickValue.value;
            path.value = clickValue.value;

            if (myElement.value) {
              positions.lng = clickValue.value[0];
              positions.lat = clickValue.value[1];

              // 使用 getElementById 获取元素
              let element = document.getElementById('lnglats') as any;
              if (element) {
                // 在这里对元素进行操作
                element.value = positions.lng + ',' + positions.lat;
              }
            }
          }

          if (e == 'click') {
            clickArray.value = [];
          }
        }

        //清除marker
        function clearMarker() {
          if (marker.value) {
            marker.value.setMap(null);
            marker.value = null;
          }
        }
        AMap.plugin(['AMap.AutoComplete', 'AMap.PlaceSearch'], function () {
          //  搜索提示
          POISearch.value = new AMap.PlaceSearch({
            city: '全国', // 搜索城市
            // citylimit: true, // 限制搜索城市
            extensions: 'all',
            map: map.value,
          });

          const autoComplete = new AMap.AutoComplete({
            input: 'tipinput', // 绑定输入提示功能的input的DOM ID
            // output: 'tip',
          });

          autoComplete.on('select', function (e) {
            //TODO 针对选中的poi实现自己的功能
            POISearch.value.search(e.poi.name);
            POISearch.value.setCity(e.poi.adcode);
            path.value = [e.poi.location.lng, e.poi.location.lat];
            if (myElement.value) {
              positions.lng = e.poi.location.lng;
              positions.lat = e.poi.location.lat;

              // 使用 getElementById 获取元素
              let element = document.getElementById('lnglats') as any;
              if (element) {
                // 在这里对元素进行操作
                element.value = positions.lng + ',' + positions.lat;
              }
            }
          });
          POISearch.value.on('markerClick', function (e) {
            current_position.value = [e.event.lnglat.lng, e.event.lnglat.lat];
            path.value = [e.event.lnglat.lng, e.event.lnglat.lat];
            if (myElement.value) {
              positions.lng = e.event.lnglat.getLng();
              positions.lat = e.event.lnglat.getLat();

              // 使用 getElementById 获取元素
              let element = document.getElementById('lnglats') as any;
              if (element) {
                // 在这里对元素进行操作
                element.value = positions.lng + ',' + positions.lat;
              }
            }
          });
        });
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const onSubmit = () => {
    emit('submitMap', path.value);
    map.value = null;
  };

  const closeMap = () => {
    emit('closeMap');
    map.value = null;
  };

  // 调用高德地图 PlaceSearch 方法，获取位置信息列表
  const getPOIList = (keywords) => {
    POISearch.value.search(keywords, (status, res) => {
      if (status === 'complete' && res.info === 'OK') {
        POIList.value = res.poiList.pois;
      }
    });
  };

  watch(
    () => props.dialogMap,
    () => {
      if (props.dialogMap == true) {
        initMap();
        //清除输入框
        let element = document.getElementById('tipinput') as any;
        if (element) {
          setTimeout(() => {
            element.value = '';
          }, 20);
        }
      }
    },
  );
</script>
<style lang="less" scoped>
  .map {
    &-search {
      margin-bottom: 16px;

      .location {
        justify-content: center;
      }
    }
  }
  .btn {
    float: right;
    // padding: 16px 0 20px 0;
  }

  .margin-left2 {
    margin-left: 8px;
  }
</style>
<style scoped>
  .location :deep(.ant-input-disabled, .ant-input[disabled]) {
    color: #444444;
    background-color: #f5f6f7;
    -webkit-text-fill-color: #444444;
  }
</style>
